package security;

import java.security.InvalidKeyException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author Tom
 */
public class AESKey 
{    
    private static final String ALGORITHM = "AES";
    public SecretKey secretKey;
    
    public AESKey(String random)
    {
        try 
        {
            KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);            
            keyGen.init(128, new SecureRandom(random.getBytes()));
            secretKey = keyGen.generateKey();
        } 
        catch (NoSuchAlgorithmException ex) 
        {
            //ex.printStackTrace();
        }
    }
    
    public AESKey(byte[] keyEncoded)
    {        
        secretKey = new SecretKeySpec(keyEncoded, ALGORITHM);
    }

    public byte[] getKeyEncoded()
    {
        return secretKey.getEncoded();
    }
    
    public byte[] encode(byte[] data)
    {
        try
        {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return cipher.doFinal(data);
        } 
        catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException |
                NoSuchAlgorithmException | NoSuchPaddingException ex) {
            //ex.printStackTrace();
        }
        return null;
    }
    
    public byte[] decode(byte[] data) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchPaddingException
    {     
        try 
        {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);  
            return cipher.doFinal(data);
        } 
        catch (NoSuchAlgorithmException ex)
        {
            //ex.printStackTrace();
        }
        return null;
    }

    
}
